<script>
import { h, resolveComponent, getCurrentInstance } from 'vue'
import { filterAttr, replaceValue } from '../../common/util'
import Body from '../../container/body/index.vue'

export default {
  name: 'LibCom',
  components: {
    LowCodeBody: Body
  },
  props: {
    schema: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const instance = getCurrentInstance()
    const schema = props.schema
    const slot = schema.slots || {}
    const slotObj = {}
    const reflectAttr = schema.reflectAttr || {}
    const attrs = {
      ...filterAttr(schema),
      ...reflectAttr
    }

    const attr = {}
    for (const key in attrs) {
      const value = attrs[key]
      attr[key] = replaceValue(value, instance)
    }

    for (const key in slot) {
      slotObj[key] = () =>
        h(resolveComponent('LowCodeBody'), {
          body: slot[key]
        })
    }
    if (schema.body) {
      return () =>
        h(resolveComponent(schema.type), attr, {
          default: () =>
            h(resolveComponent('LowCodeBody'), {
              body: schema.body
            }),
          ...slotObj
        })
    }
    return () => h(resolveComponent(schema.type), attrs)
  }
}
</script>
